import { defineStore } from "pinia"
import { Login, Logout } from "@/service/api"
import Storage from "@/utils/storage"
import router from "@/router"
import type { loginState, account } from "../type"
import { ElMessage } from "element-plus"
// import { mainStore } from "@/stores/modules/main"

export const loginStore = defineStore({
  //js命名
  id: "login",
  // 数据
  state: (): loginState => {
    return {
      token: Storage.getStorage("token")
    }
  },
  // computed 修饰一些值
  getters: {},
  // methods, 同步和异步都可以, 修改state
  actions: {
    // 登录
    async Login(data: account) {
      const res = await Login(data)
      if (res.message === "登录成功") {
        this.token = res.token
        Storage.setStorage("token", res.token)
        // const mainstore = mainStore()
        // 初始化菜单和按钮权限
        // mainstore.getInit()
        ElMessage.success(res.message)
        router.push("/home")
      }
    },
    // 退出登录
    async Logout() {
      const res = await Logout()
      if (res.message === "退出登录成功") {
        this.token = undefined
        Storage.deleteStorage("token")
        ElMessage.success(res.message)
        router.push("/login")
      }
    }
  }
})
